<template>
  <div class="account-manage">
    <!-- 账户列表 -->
    <el-card class="account-list">
      <template #header>
        <div class="card-header">
          <span>账户列表</span>
          <div class="search-group">
            <el-select
    v-model="currentCustomerId"
    placeholder="选择客户查询账户"
    style="width: 200px; margin-right: 10px"
    @change="getCustomerAccounts(currentCustomerId)"
    filterable
  >
    <el-option label="全部客户" value="" />
    <el-option
      v-for="customer in customers"
      :key="customer.customer_id"
      :label="`${customer.user_name} (${customer.customer_id})`"
      :value="customer.customer_id"
    />
  </el-select>

            <el-select
              v-model="currentBranchId"
              placeholder="选择支行查询账户"
              style="width: 200px"
              @change="getBranchAccounts(currentBranchId)"
            >
              <el-option label="全部支行" value="" />
              <el-option
                v-for="branch in branches"
                :key="branch.branch_id"
                :label="branch.branch_name"
                :value="branch.branch_id"
              />
            </el-select>
            <el-button type="primary" @click="openAddDialog">添加账户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="paginatedAccounts" v-loading="loading" style="width: 100%">
        <el-table-column prop="account_id" label="账户ID" width="180" />
        <el-table-column prop="customer_id" label="客户ID" width="180" />
        <el-table-column prop="branch_id" label="支行ID" width="180" />
        <el-table-column prop="account_type" label="账户类型" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.account_type === '储蓄用户' ? 'success' : 'warning'">
              {{ scope.row.account_type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="scope">
            ¥{{ scope.row.balance.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="open_date" label="开户日期" width="180">
  <template #default="scope">
    {{ scope.row.open_date || '未设置' }}
  </template>
</el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="showTransactionDialog(scope.row.account_id)"
            >
              交易
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteAccount(scope.row.account_id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="summary-info" v-if="accounts.length > 0">
        <el-tag type="info">账户总数: {{ accounts.length }}</el-tag>
        <el-tag type="success">总余额: ¥{{ totalBalance.toFixed(2) }}</el-tag>
      </div>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </el-card>

    <!-- 新建账户弹窗 -->
    <el-dialog
  v-model="addDialogVisible"
  title="新建账户"
  @close="resetAddForm"
>
  <el-form :model="newAccount" label-width="120px" :rules="accountRules" ref="accountFormRef">
    <el-form-item label="客户" prop="customer_id">
  <el-select 
    v-model="newAccount.customer_id" 
    filterable
    placeholder="请选择客户"
    style="width: 100%"
    @change="handleCustomerSelect"
  >
    <el-option
      v-for="customer in customers"
      :key="customer.customer_id"
      :label="`${customer.user_name} (${customer.phone})`"
      :value="customer.customer_id"
    />
  </el-select>
</el-form-item>
    <el-form-item label="支行" prop="branch_id">
      <el-select v-model="newAccount.branch_id" style="width: 100%">
        <el-option
          v-for="branch in branches"
          :key="branch.branch_id"
          :label="branch.branch_name"
          :value="branch.branch_id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="账户类型" prop="account_type">
      <el-select v-model="newAccount.account_type" style="width: 100%">
        <el-option label="储蓄用户" value="储蓄用户" />
        <el-option label="支票用户" value="支票用户" />
      </el-select>
    </el-form-item>
    <el-form-item label="初始余额" prop="balance">
      <el-input-number 
        v-model="newAccount.balance" 
        :min="0" 
        :precision="2"
        style="width: 100%" 
      />
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="addDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="createAccount">保存</el-button>
  </template>
</el-dialog>

    <!-- 交易对话框 -->
    <el-dialog v-model="transactionDialogVisible" title="账户交易" width="500px">
      <el-form :model="transactionForm" label-width="120px" :rules="transactionRules" ref="transactionFormRef">
        <el-form-item label="账户ID">
          <el-input v-model="transactionForm.accountId" disabled />
        </el-form-item>
        <el-form-item label="交易类型" prop="transactionType">
          <el-select v-model="transactionForm.transactionType" style="width: 100%">
            <el-option label="存款" value="存款" />
            <el-option label="取款" value="取款" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number 
            v-model="transactionForm.amount" 
            :min="0.01" 
            :precision="2"
            style="width: 100%" 
          />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="transactionForm.note" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="transactionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="executeTransaction">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request.js'

// 数据定义
const accounts = ref([])
const customers = ref([])
const currentCustomerId = ref('')
const currentBranchId = ref('')
const loading = ref(false)
const branches = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 新建账户表单数据
const newAccount = ref({
  customer_id: '',
  branch_id: '',
  account_type: '储蓄用户',
  balance: 0
})

const transactionForm = ref({
  account_id: '',      
  transactionType: '存款',
  amount: 0,          
  note: ''
});

const transactionDialogVisible = ref(false)
const accountFormRef = ref(null)
const transactionFormRef = ref(null)
const addDialogVisible = ref(false)

// 表单验证规则
const accountRules = {
  customerId: [{ required: true, message: '请输入客户ID', trigger: 'blur' }],
  branchId: [{ required: true, message: '请选择支行', trigger: 'change' }],
  accountType: [{ required: true, message: '请选择账户类型', trigger: 'change' }],
  balance: [{ required: true, message: '请输入初始余额', trigger: 'blur' }]
}

const transactionRules = {
  transactionType: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ]
}

// 计算总余额
const totalBalance = computed(() => {
  return accounts.value.reduce((sum, account) => sum + account.balance, 0)
})

// 计算属性处理前端分页
const paginatedAccounts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return accounts.value.slice(start, end);
});

// 获取支行列表
const getBranches = async () => {
  try {
    const response = await request.get('/branches/getAll')
    if (response.code === 0) {
      branches.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取支行列表失败')
  }
}
// 获取所有客户
const getAllCustomers = async () => {
  try {
    const response = await request.get('/customers/getAll')
    if (response.code === 0) {
      customers.value = response.data
    }
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  }
}

// 获取所有账户
const getAllAccounts = async () => {
  try {
    loading.value = true
    const response = await request.get('/accounts/getAll')
    accounts.value = response.data || []
    total.value = accounts.value.length
  } catch (error) {
    ElMessage.error('获取账户列表失败')
    accounts.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}
// 获取指定客户的所有账户
const getCustomerAccounts = async (customerId) => {
  if (!customerId) return
  try {
    loading.value = true
    const response = await request.get('/accounts/getByCustomerId', { 
      params: { customer_id: customerId }
    })
    accounts.value = response.data || []
    total.value = accounts.value.length
  } catch (error) {
    ElMessage.error('获取账户列表失败')
    accounts.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取指定支行的所有账户
const getBranchAccounts = async (branchId) => {
  if (!branchId) {
    await getAllAccounts();
    return;
  }
  try {
    loading.value = true;
    const response = await request.get('/accounts/getByBranchId', { 
      params: { branch_id: branchId }
    });
    accounts.value = response.data || [];
    total.value = accounts.value.length;
  } catch (error) {
    ElMessage.error('获取支行账户失败');
    accounts.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 打开添加弹窗
const openAddDialog = () => {
  addDialogVisible.value = true;
}

// 重置添加表单
const resetAddForm = () => {
  accountFormRef.value?.resetFields();
  newAccount.value = {
    customerId: '',
    branchId: '',
    accountType: '储蓄用户',
    balance: 0
  };
}

// 创建新账户
const createAccount = async () => {
  try {
    await accountFormRef.value.validate()
    if (!newAccount.value.customerId) {
      ElMessage.error('请选择客户')
      return
    }
    
    console.log('提交的数据:', { 
      customerId: newAccount.value.customer_id,
      branchId: newAccount.value.branch_id,
      accountType: newAccount.value.account_type,
      balance: newAccount.value.balance
    })
    const response = await request.post('/accounts', newAccount.value)
    if (response.code === 0) {
      ElMessage.success('账户创建成功')
      addDialogVisible.value = false
      // 刷新当前显示的账户列表
      if (currentCustomerId.value) {
        getCustomerAccounts(currentCustomerId.value)
      } else {
        getAllAccounts()
      }
      resetAddForm()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('账户创建失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 选择客户时的处理
const handleCustomerSelect = (value) => {
  console.log('选择的客户ID:', value) // 调试日志
  newAccount.value.customer_id = value
}

// 删除账户
const deleteAccount = async (accountId) => {
  try {
    await ElMessageBox.confirm('确定要删除此账户吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const account = { account_id: accountId }
    const response = await request.delete('/accounts', { data: account })
    if (response.code === 0) {
      ElMessage.success('账户删除成功')
      // 无论是否选择客户，直接刷新全部账户列表
      getAllAccounts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('账户删除失败')
    }
  }
}

// 显示交易对话框
const showTransactionDialog = (accountId) => {
  transactionForm.value.account_id = accountId
  transactionForm.value.amount = 0
  transactionForm.value.note = ''
  transactionDialogVisible.value = true
}

// 执行交易
const executeTransaction = async () => {
  try {
    await transactionFormRef.value.validate();

    const requestData = {
      account_id: transactionForm.value.account_id, 
      balance: transactionForm.value.transactionType === '存款' 
               ? transactionForm.value.amount 
               : -transactionForm.value.amount      // 取款转为负数
    };

    const response = await request.put('/accounts/updateBalance', requestData);
    if (response.code === 0) {
      ElMessage.success('交易成功');
      transactionDialogVisible.value = false;
      // 刷新列表
      if (currentCustomerId.value) {
        await getCustomerAccounts(currentCustomerId.value);
      } else {
        await getAllAccounts();
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('交易失败: ' + (error.response?.data?.message || error.message));
    }
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  if (currentCustomerId.value) {
    getCustomerAccounts(currentCustomerId.value);
  } else if (currentBranchId.value) {
    getBranchAccounts(currentBranchId.value);
  }else {
    // 当没有选择客户或分行时，加载所有账户
    getAllAccounts();
  }
};

const handleCurrentPageChange = (val) => {
  currentPage.value = val;
  if (currentCustomerId.value) {
    getCustomerAccounts(currentCustomerId.value);
  } else if (currentBranchId.value) {
    getBranchAccounts(currentBranchId.value);
  }else {
    // 当没有选择客户或分行时，加载所有账户
    getAllAccounts();
  }
};

onMounted(async () => {
  await getBranches()
  await getAllCustomers()
  await getAllAccounts() 
})
</script>

<style scoped>
.account-manage {
  padding: 20px;
}

.account-list,
.account-form {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-group {
  display: flex;
  align-items: center;
}

.summary-info {
  margin-top: 20px;
  display: flex;
  gap: 20px;
}
</style>